package com.msxt.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msxt.annotation.IgnoreAuth;
import com.msxt.dto.ChatMessage;
import com.msxt.dto.ZaixiankefuDTO;
import com.msxt.dto.ZaixiankefuEntity;
import com.msxt.result.R;
import com.msxt.service.ChatMessageService;
import com.msxt.service.ZaixiankefuService;
import com.msxt.utils.MPUtil;
import com.msxt.utils.PageUtils;
import com.msxt.view.ZaixiankefuView;
import com.msxt.websocket.WebSocketServer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/zaixiankefu")
public class ZaixiankefuController {

	@Autowired
	private ZaixiankefuService zaixiankefuService;

	@Autowired
	private ChatMessageService chatMessageService;

	@Autowired
	private WebSocketServer webSocketServer;

	@PostMapping("/sendMessage")
	@Transactional
	public R sendMessage(@RequestBody ChatMessage chatMessage, HttpServletRequest request) {
		try {
			String tableName = (String) request.getAttribute("tableName");
			String username = (String) request.getAttribute("username");

			if ("shangjia".equals(tableName)) {
				chatMessage.setSenderType("merchant");
				chatMessage.setSenderId(username);
			} else if ("yonghu".equals(tableName)) {
				chatMessage.setSenderType("user");
				chatMessage.setSenderId(username);
			}

			chatMessage.setTimestamp(System.currentTimeMillis());
			chatMessage.setIsRead(0);

			// 关键修复：确保咨询记录存在
			if (StringUtils.isNotBlank(chatMessage.getConsultBianhao())) {
				QueryWrapper<ZaixiankefuEntity> wrapper = new QueryWrapper<>();
				wrapper.eq("bianhao", chatMessage.getConsultBianhao());
				Long count = zaixiankefuService.count(wrapper);
				if (count == 0) {
					return R.error("咨询记录不存在，咨询编号: " + chatMessage.getConsultBianhao());
				}
			}

			Long messageId = chatMessageService.saveMessage(chatMessage);
			chatMessage.setId(messageId);

			String messageJson = JSON.toJSONString(chatMessage);
			webSocketServer.sendToConsult(chatMessage.getConsultBianhao(), messageJson);

			return R.ok().put("data", chatMessage);
		} catch (DataIntegrityViolationException e) {
			e.printStackTrace();
			return R.error("咨询记录不存在，无法发送消息");
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("发送消息失败: " + e.getMessage());
		}
	}

	@GetMapping("/chatHistory/{consultBianhao}")
	public R getChatHistory(@PathVariable("consultBianhao") String consultBianhao) {
		try {
			List<ChatMessage> messages = chatMessageService.getMessagesByConsultBianhao(consultBianhao);
			return R.ok().put("data", messages);
		} catch (Exception e) {
			return R.error("获取聊天记录失败");
		}
	}

	@PostMapping("/save")
	@Transactional
	public R save(@RequestBody ZaixiankefuEntity zaixiankefu, HttpServletRequest request) {
		try {
			zaixiankefu.setId(null);
			zaixiankefu.setAddtime(new Date());

			// 设置初始咨询内容的时间戳
			if (StringUtils.isNotBlank(zaixiankefu.getNeirong())) {
				zaixiankefu.setNeirongTime(System.currentTimeMillis());
			}

			zaixiankefuService.save(zaixiankefu);
			return R.ok().put("data", zaixiankefu);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("保存咨询失败");
		}
	}

	@PostMapping("/update")
	@Transactional
	public R update(@RequestBody ZaixiankefuEntity zaixiankefu, HttpServletRequest request) {
		try {
			// 设置商家回复的时间戳
			if (StringUtils.isNotBlank(zaixiankefu.getShhf())) {
				zaixiankefu.setShhfTime(System.currentTimeMillis());
			}

			zaixiankefuService.updateById(zaixiankefu);
			return R.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("修改失败");
		}
	}

	@GetMapping("/onlineCount/{consultBianhao}")
	public R getOnlineCount(@PathVariable("consultBianhao") String consultBianhao) {
		try {
			int onlineCount = webSocketServer.getOnlineUserCount(consultBianhao);
			return R.ok().put("data", onlineCount);
		} catch (Exception e) {
			return R.error("获取在线人数失败");
		}
	}

	@PostMapping("/markAsRead")
	public R markAsRead(@RequestParam Long messageId, HttpServletRequest request) {
		try {
			String username = (String) request.getAttribute("username");
			chatMessageService.markMessageAsRead(messageId, username);
			return R.ok();
		} catch (Exception e) {
			return R.error("标记已读失败");
		}
	}

	@GetMapping("/info/{id}")
	public R info(@PathVariable("id") Long id) {
		ZaixiankefuEntity zaixiankefu = zaixiankefuService.getById(id);
		if (zaixiankefu == null) {
			return R.error("咨询记录不存在");
		}

		List<ChatMessage> chatHistory = chatMessageService.getMessagesByConsultBianhao(zaixiankefu.getBianhao());
		Map<String, Object> result = new HashMap<>();
		result.put("consultInfo", zaixiankefu);
		result.put("chatHistory", chatHistory);
		result.put("onlineCount", webSocketServer.getOnlineUserCount(zaixiankefu.getBianhao()));
		return R.ok().put("data", result);
	}

	@GetMapping("/page")
	public R page(@RequestParam Map<String, Object> params,
				  ZaixiankefuEntity zaixiankefu,
				  HttpServletRequest request) {
		String tableName = (String) request.getAttribute("tableName");
		String username = (String) request.getAttribute("username");

		QueryWrapper<ZaixiankefuEntity> wrapper = new QueryWrapper<>();

		if (tableName != null && username != null) {
			if ("shangjia".equals(tableName)) {
				wrapper.eq("shangjiazhanghao", username);
			} else if ("yonghu".equals(tableName)) {
				wrapper.eq("yonghuzhanghao", username);
			}
		}

		MPUtil.likeOrEq(wrapper, zaixiankefu);

		PageUtils page = zaixiankefuService.queryPage(params,
				MPUtil.sort(MPUtil.between(wrapper, params), params));
		return R.ok().put("data", page);
	}

	@IgnoreAuth
	@GetMapping("/list")
	public R list(@RequestParam Map<String, Object> params,
				  ZaixiankefuEntity zaixiankefu,
				  HttpServletRequest request) {
		QueryWrapper<ZaixiankefuEntity> wrapper = new QueryWrapper<>();
		MPUtil.likeOrEq(wrapper, zaixiankefu);
		PageUtils page = zaixiankefuService.queryPage(params,
				MPUtil.sort(MPUtil.between(wrapper, params), params));
		return R.ok().put("data", page);
	}

	@GetMapping("/lists")
	public R list(ZaixiankefuEntity zaixiankefu) {
		QueryWrapper<ZaixiankefuEntity> wrapper = new QueryWrapper<>();
		wrapper.allEq(MPUtil.allEQMapPre(zaixiankefu, "zaixiankefu"));
		return R.ok().put("data", zaixiankefuService.list(wrapper));
	}

	@GetMapping("/query")
	public R query(ZaixiankefuEntity zaixiankefu) {
		QueryWrapper<ZaixiankefuEntity> wrapper = new QueryWrapper<>();
		wrapper.allEq(MPUtil.allEQMapPre(zaixiankefu, "zaixiankefu"));
		ZaixiankefuView zaixiankefuView = zaixiankefuService.selectView(wrapper);
		return R.ok("查询在线客服成功").put("data", zaixiankefuView);
	}

	@GetMapping("/detail/{id}")
	public R detail(@PathVariable("id") Long id) {
		ZaixiankefuDTO zaixiankefuDTO = zaixiankefuService.getZaixiankefuDetailWithMessages(id);

		if (zaixiankefuDTO == null) {
			return R.error("数据不存在");
		}

		Map<String, Object> result = new HashMap<>();
		result.put("id", zaixiankefuDTO.getId());
		result.put("bianhao", zaixiankefuDTO.getBianhao());
		result.put("allMessages", zaixiankefuDTO.getAllMessages());
		result.put("userMessages", zaixiankefuDTO.getUserMessages());
		result.put("merchantMessages", zaixiankefuDTO.getMerchantMessages());

		return R.ok().put("data", result);
	}

	@PostMapping("/add")
	public R add(@RequestBody ZaixiankefuEntity zaixiankefu,
				 HttpServletRequest request) {
		try {
			zaixiankefu.setId(null);
			zaixiankefu.setAddtime(new Date());
			zaixiankefuService.save(zaixiankefu);
			return R.ok().put("data", zaixiankefu);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("创建咨询失败");
		}
	}

	@DeleteMapping("/delete")
	@Transactional
	public R delete(@RequestBody Long[] ids, HttpServletRequest request){
		try {
			String tableName = (String) request.getAttribute("tableName");
			String username = (String) request.getAttribute("username");

			List<ZaixiankefuEntity> deletedRecords = new ArrayList<>();

			for (Long id : ids) {
				ZaixiankefuEntity entity = zaixiankefuService.getById(id);
				if (entity == null) {
					return R.error("ID为 " + id + " 的记录不存在");
				}

				deletedRecords.add(entity);

				if ("shangjia".equals(tableName) && !entity.getShangjiazhanghao().equals(username)) {
					return R.error("您没有权限删除ID为 " + id + " 的记录");
				}

				if ("yonghu".equals(tableName) && !entity.getYonghuzhanghao().equals(username)) {
					return R.error("您没有权限删除ID为 " + id + " 的记录");
				}

				QueryWrapper<ChatMessage> wrapper = new QueryWrapper<>();
				wrapper.eq("consult_bianhao", entity.getBianhao());
				chatMessageService.remove(wrapper);
			}

			boolean deleteSuccess = zaixiankefuService.removeByIds(Arrays.asList(ids));

			if (deleteSuccess) {
				Map<String, Object> result = new HashMap<>();
				result.put("deletedIds", ids);
				result.put("deletedCount", ids.length);
				return R.ok(result);
			} else {
				return R.error("删除失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("删除失败: " + e.getMessage());
		}
	}

	@GetMapping("/remind/{columnName}/{type}")
	public R remindCount(@PathVariable("columnName") String columnName,
						 HttpServletRequest request,
						 @PathVariable("type") String type,
						 @RequestParam Map<String, Object> map) {
		map.put("column", columnName);
		map.put("type", type);

		if("2".equals(type)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			Date remindStartDate = null;
			Date remindEndDate = null;
			if(map.get("remindstart") != null) {
				Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH, remindStart);
				remindStartDate = c.getTime();
				map.put("remindstart", sdf.format(remindStartDate));
			}
			if(map.get("remindend") != null) {
				Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH, remindEnd);
				remindEndDate = c.getTime();
				map.put("remindend", sdf.format(remindEndDate));
			}
		}

		QueryWrapper<ZaixiankefuEntity> wrapper = new QueryWrapper<>();
		if(map.get("remindstart") != null) {
			wrapper.ge(columnName, map.get("remindstart"));
		}
		if(map.get("remindend") != null) {
			wrapper.le(columnName, map.get("remindend"));
		}

		String tableName = (String) request.getAttribute("tableName");
		String username = (String) request.getAttribute("username");

		if (tableName != null && username != null) {
			if ("shangjia".equals(tableName)) {
				wrapper.eq("shangjiazhanghao", username);
			}
			if ("yonghu".equals(tableName)) {
				wrapper.eq("yonghuzhanghao", username);
			}
		}

		long count = zaixiankefuService.count(wrapper);
		return R.ok().put("count", count);
	}
}